package com.example.vlille2.parser;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;
import android.util.Log;

import com.example.vlille2.base.StationsBDD;

public class StationHandler extends DefaultHandler {

	private Context contexte;
	
	private static final String BALISE_ADRESSE = "adress";
	private static final String BALISE_STATUS = "status";
	private static final String BALISE_BIKES = "bikes";
	private static final String BALISE_ATTACHS = "attachs";
	private static final String BALISE_PAIEMENT = "paiement";
	
	private static final String STATUS_OK = "0";
	private static final String PAIEMENT_AVEC = "AVEC_TPE";
	private static final String PAIEMENT_SANS = "SANS_TPE";
	
	private int idStation;
	
	private String adresse;
	private boolean statut;
	private int velos;
	private int places;
	private boolean paiement;
	
	private List<String> pileBalises;
	private String texte_tmp;
	
	public StationHandler(Context contexte)
	{
		super();
		this.contexte = contexte;
	}
	
	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		
		adresse = null;
		statut = true;
		velos = 0;
		places = 0;
		paiement = false;
		pileBalises = new ArrayList<String>();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		
		pileBalises.add(qName);
		texte_tmp = "";
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		super.characters(ch, start, length);
		texte_tmp+= new String(ch, start, length);
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		super.endElement(uri, localName, qName);
		
		if (qName.equals(BALISE_ADRESSE)) adresse = texte_tmp;
		else if (qName.equals(BALISE_STATUS)) statut = Boolean.parseBoolean(texte_tmp);
		else if (qName.equals(BALISE_BIKES)) velos = Integer.parseInt(texte_tmp);
		else if (qName.equals(BALISE_ATTACHS)) places = Integer.parseInt(texte_tmp);
		else if (qName.equals(BALISE_PAIEMENT)) paiement = texte_tmp.equals(PAIEMENT_AVEC);		
		
		pileBalises.remove(pileBalises.size()-1);
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
		StationsBDD bdd = StationsBDD.getInstance();
		bdd.open();
		bdd.modifierStation(idStation,adresse,statut,velos,places,paiement);
		bdd.close();
	}

	public void setIdStation(int idStation) {
		this.idStation = idStation;
	}
}
